package gw.com.android.ui.trade;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import butterknife.BindView;
import gw.com.android.app.AppContances;
import gw.com.android.app.GTConfig;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.ui.BaseActivity;
import gw.com.android.ui.dialog.OrderOutTimeDialog;
import gw.com.android.ui.dialog.PopupDoubleBtnDialog;
import gw.com.android.ui.trade.Fragment.BaseOrderFragment;
import gw.com.android.ui.trade.Fragment.OrderFailFragment;
import gw.com.android.ui.trade.Fragment.OrderSucFragment;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.util.NetworkMonitor;
import www.com.library.view.BtnClickListener;

/**
 * 所有交易界面公共类
 *
 * @author Administrator
 * O
 */
public abstract class TradeOrderActivity extends BaseActivity {

    /**
     * 错误提示
     */
    @BindView(R.id.morder_alarm_title)
    TextView m_errorTextView;
    /**
     * 加载圈,进入界面加载数据
     */
    @BindView(R.id.loading_progress_layout)
    View mProgress;
    /**
     * 加载圈2,下单时显示
     */
    @BindView(R.id.loading_view_layout)
    View mProgressLayout;
    public String mTypeTag = AppContances.TAB_ID_CREATE_ORDER; //获取市价处理类型，市价开仓，挂单，平仓，设置，改单等
    public OrderFailFragment mFailFragment;
    public OrderSucFragment mSucFragment;
    /**
     * 进入交易界面的入口类型
     */
    public int mFromType = AppContances.TRADE_TYPE_FORM_QUOTE;
    public PopupDoubleBtnDialog mBackDialog;

    /**
     * 标识当前相关订单是否已经处理完成
     */
    public boolean hasCommitFinish = true;

    /**
     * 下单数据存放对象
     */
    public DataItemDetail mDetailItem = new DataItemDetail();

    public int resultType = 0;//交易状态

    /**
     * 手数是否发现变化
     */
    public boolean hasChangeLot = false;
    /**
     * 偏移量是否发现变化
     */
    public boolean hasChangeRange = false;
    public String mPrdName = "";//产品名
    public int mUiCode;//产品code
    public int mTradeDir = AppContances.TRADE_TYPE_BUY; //买卖方向
    public static TradeOrderActivity mInstance = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInstance = this;
        hasCommitFinish = true;
        hasChangeLot = false;
        hasChangeRange = false;
    }

    @Override
    public int getLayoutView() {
        return R.layout.activity_order_base;
    }

    @Override
    protected void initLayoutView() {
        //mTitleBar.setLeftResource(R.string.order_type_position);
        mTitleBar.setAppTitle(R.string.order_type_modify_market);

        mTitleBar.setBtnClickListener(new BtnClickListener() {

            @Override
            public void onBtnClick(int viewID) {
                if (viewID == R.id.title_left_icon) {
                    onLeftClick();
                } else if (viewID == R.id.title_right_icon) {
                    onRightClick();
                }
            }
        });

        mProgress.setOnClickListener(this);

        mProgressLayout.setVisibility(View.VISIBLE);

        m_errorTextView.setOnClickListener(this);

        mHandler.sendEmptyMessage(AppContances.HANDLER_SHOW_VIEW);
    }

    @Override
    protected void onSendQuote() {
        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(mUiCode));
    }

	/*@OnClick(R.id.title_left_btn)
	void onBack(){
		finish();
	}*/

    /**
     * 展示交易成功界面
     */
    protected void showOrderFragment() {
        mTitleBar.setVisibility(View.VISIBLE);
    }

    /**
     * 展示交易成功界面
     */
    protected void showOrderSucFragment(DataItemDetail mDetail) {
        mTitleBar.setVisibility(View.GONE);
    }

    /**
     * 展示交易失败界面
     */
    protected void showOrderFailFragment(DataItemDetail mDetail) {
        mTitleBar.setVisibility(View.GONE);
    }


    public abstract void onSymbolUpdateNotify();

    public void onSymbolNotify(DataItemDetail tickModel) {
    }

    ;

    /**
     * 超时弹层提示
     *
     * @param bundleFail
     */
    public void timeOutFail(Bundle bundleFail) {
        Logger.e("onOrderFailNotify 下单超时失败处理逻辑 mSeq = " + ((BaseOrderFragment) mCurrentFragment).mSeq + ", notifyId = " + bundleFail.getInt("iNotification") + ", resultCode = " + bundleFail.getInt("iValue"));
        if (null != mCurrentFragment && mCurrentFragment instanceof BaseOrderFragment) {
            //确保是这次的下单操作结果
            if (((BaseOrderFragment) mCurrentFragment).mSeq == bundleFail.getInt("iNotification")) {
                hideLoading();
                resultType = AppContances.HANDLER_ORDER_TIME_OUT;
                if (!GTConfig.instance().mHasKickOut) {
                    OrderOutTimeDialog.showOrderOutTimeDialog(this);
                }
            }
        }
    }

    ;

    /**
     * 显示加载圈
     */
    public void showLoading() {
        if (mCurrentTag.equals(AppContances.TAB_ID_SUC_ORDER) || mCurrentTag.equals(AppContances.TAB_ID_FAILURE_ORDER)) {
            return;
        }
        mProgress.setVisibility(View.VISIBLE);
        // 启动定时任务
        hasCommitFinish = false;
    }

    /**
     * 隐藏加载圈
     */
    public void hideLoading() {
        if (null != mProgress) {
            mProgress.setVisibility(View.GONE);
        }
        hasCommitFinish = true;
    }

    @Override
    public void registerRxBus() {
        super.registerRxBus();
        Disposable quoteAllRegister = RxBus.getInstance().registertoObservableSticky(GTSConst.REPLY_SYMBOL_ALLLIST + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundle) throws Exception {
                        onSymbolUpdateNotify();
                        DataItemDetail model = DataManager.instance().getTickModel(mUiCode);
                        onSymbolNotify(model);
                    }
                });
        bindSubscription(quoteAllRegister);

        Disposable quoteUpdateRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        if (model.getInt(GTSConst.JSON_KEY_CODEID) == mUiCode) {
                            onSymbolUpdateNotify();
                        }
                        if (model.getInt(GTSConst.JSON_KEY_CODEID) == mUiCode || GTSConst.CNY_CODE == model.getInt(GTSConst.JSON_KEY_CODEID)) {
                            if (null != model) {
                                onSymbolNotify(model);
                            }
                        }
                    }
                });

        bindSubscription(quoteUpdateRegister);

        Disposable quoteTickRegister = RxBus.getInstance().register(GTSConst.REPLY_SYMBOL_TICK_UPDATE + "", DataItemDetail.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DataItemDetail>() {

                    @Override
                    public void accept(@NonNull DataItemDetail model) throws Exception {
                        if (model.getInt(GTSConst.JSON_KEY_CODEID) == mUiCode || GTSConst.CNY_CODE == model.getInt(GTSConst.JSON_KEY_CODEID)) {
                            if (null != model) {
                                onSymbolNotify(model);
                            }
                        }
                    }
                });

        bindSubscription(quoteTickRegister);

        Disposable successRegister = RxBus.getInstance().register(GTSConst.REPLY_ORDER_SUCCESS + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundleSuc) throws Exception {
                        if (null != bundleSuc && null != mCurrentFragment && mCurrentFragment instanceof BaseOrderFragment) {
                            ((BaseOrderFragment) mCurrentFragment).onOrderSuccessNotify(bundleSuc.getInt("iNotification"), bundleSuc.getInt("iValue"), (DataItemDetail) bundleSuc.getParcelable("model"));
                        }
                    }
                });

        bindSubscription(successRegister);

        Disposable failRegister = RxBus.getInstance().register(GTSConst.REPLY_ORDER_FAILED + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Bundle>() {

                    @Override
                    public void accept(@NonNull Bundle bundleFail) throws Exception {
                        if (null != bundleFail && null != mCurrentFragment && mCurrentFragment instanceof BaseOrderFragment) {
                            if (bundleFail.getInt("iValue") != AppContances.HANDLER_ORDER_TIME_OUT) {
                                ((BaseOrderFragment) mCurrentFragment).onOrderFailNotify(bundleFail.getInt("iNotification"), bundleFail.getInt("iValue"));
                            } else {
                                timeOutFail(bundleFail);
                            }
                        }
                    }
                });

        bindSubscription(failRegister);
    }

    public Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case AppContances.HANDLER_SHOW_VIEW:
                    showOrderFragment();
                    break;
                case AppContances.HANDLER_RESULT_SUC:
                    hideLoading();
                    if (hasCommitFinish) {
                        showOrderSucFragment(mDetailItem);
                    }
                    break;
                case AppContances.HANDLER_SERVER_FAIL:
                    hideLoading();
                    if (hasCommitFinish) {
                        showOrderFailFragment(mDetailItem);
                    }
                    break;
            }
        }
    };

    /**
     * 各交易界面返回按钮提示信息
     *
     * @param act
     * @return
     */
    public PopupDoubleBtnDialog getOrderBack(final Activity act) {
        PopupDoubleBtnDialog mDialog = PopupDoubleBtnDialog.newInstance(act, getString(R.string.exist_dialog_title), getString(R.string.order_result_order_status),
                new BtnClickListener() {

                    @Override
                    public void onBtnClick(int viewID) {
                        if (viewID == R.id.action_btn_pos) {
                            finish();
                        }
                    }
                });
        return mDialog;
    }

    /**
     * 左边按钮点击事件，子类可重写此方法
     */
    protected void onLeftClick() {
        if (resultType == AppContances.HANDLER_ORDER_TIME_OUT) {
            if (NetworkMonitor.hasNetWork()) {
            }
        }
        finish();
    }

    /**
     * 右边按钮点击事件，子类可重写此方法
     */
    protected void onRightClick() {

    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!hasCommitFinish) {
                if (mBackDialog == null) {
                    mBackDialog = getOrderBack(TradeOrderActivity.this);
                    mBackDialog.show();
                }
                if (!mBackDialog.isShowing()) {
                    mBackDialog.show();
                }
            } else {
                onLeftClick();
            }
            return true;
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    public void finish() {
        super.finish();
        mInstance = null;
        if (null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        hideLoading();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mInstance = null;
        if (null != mHandler) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        hideLoading();
    }
}
